import { Input, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ApplyWithdraw, GetUserInfo, BankData, ToTurnMoney, GetChooseMethod } from '../../api/mine'
import NavBar from '../../components/Navbar'
import AmePopup from '../../components/Popup'
import appSdk from '../../utils/app_sdk'
import './index.less'
import AmeModal from './modal'
import { isIOS } from '../../utils/util'

import aliImg from '../../images/ali.png'
import bankImg from '../../images/bank.png'
import ExchangeLog from '../record_list'

// const bankData = [
//   { name: '招商银行卡（0999）', id: '668' },
//   { name: '中国银行卡（2229）', id: '667' },
//   { name: '平安银行卡（1299）', id: '857' },
// ]

const NavTab = ({ navigate }) => {
  return (
    <div className="nav_tab">
      <span className="un" onClick={() => navigate('/recharge')}>
        {window.baseConfig.coin_name}
      </span>
      <span className="active">我的收益</span>
    </div>
  )
}

// 点击立即提现：
// 1. 先判断 is_idcard  != 1  调： jumpToRealName()
// 2. 如果is_idcard == 1，然后判断  is_fase_order ,is_fase_order != 1 调：jumpToRealBank()
// 3. is_fase_order 跳转之后，我这边认证完会通知你成功。跟支付的js函数回调通知一样
// 4. 最后判断 is_pig_sign 是否 ==1 ，如果为 is_pig_sign 为0，调用 /api/pigSign 这个接口，成功回调之后拉取银行卡信息。  银行卡信息目前只有1个

function Income() {
  const navigate = useNavigate()
  const [step, setStep] = useState(1) // 1: 收入信息 2 是 准备提现
  const [visible, setVisible] = useState(false)
  // const [bankData, setBankData] = useState([]);
  // const [activeBank, setActiveBank] = useState(bankData[0]);
  const [userInfo, setUserInfo] = useState({
    service_fee: 6,
    mibi: 0,
    withdrawable_balance: 0,
    mizuan: 0,
    is_idcard: 0,
    is_fase_order: 0,
    is_pig_sign: 0,
    is_union_member: 0
  })

  const [realVisible, setRealVisible] = useState(false) // 实名认证
  const [turnVisible, setTurnVisible] = useState(false) // 转换确认
  const [withdrawVisible, setWithdrawVisible] = useState(false) // 提现确认

  const [withdrawValue, setWithdrawValue] = useState(1)
  const [turnValue, setTurnValue] = useState(1)

  const onSelectBank = () => {
    setVisible(!visible)
  }

  const [chooseMethod, setChooseMethod] = useState()
  const getInfo = () => {
    // Toast.show({
    //   icon: 'loading',
    //   content: '加载中...',
    //   duration: 2000
    // })
    GetChooseMethod().then((res) => {
      console.log('当前选中的', res)
      // bank_no ali_account type bank_name
      setChooseMethod(res.data)
    })
    // .finally(() => {
    //   console.log('关闭loading');
    //   Toast.clear()
    // })
    GetUserInfo().then((res) => {
      setUserInfo(res.data)
      // if (res.data.bank_account) {
      //   const { bank_account, bank_of_deposit } = res.data
      //   setBankData([
      //     { id: bank_account, name: `${bank_of_deposit}(${bank_account?.slice(bank_account.length - 4)})` }
      //   ])
      //   setActiveBank({ id: bank_account, name: bank_of_deposit })
      // } else {
      //   console.log('没有卡号', 'res.data.bank_account', res.data.bank_account)
      // }
    })
    // .finally(() => {
    //   console.log('关闭loading');
    //   Toast.clear()
    // })
  }
  // 签约提现
  const getPigSignInfo = () => {
    BankData().then((res) => {
      console.log('getPigSignInfo', res)
      if (res.data.jump_url) {
        window.location.href = res.data.jump_url
      }
    })
  }

  useEffect(() => {
    getInfo()
  }, [])

  const applyData = () => {
    if (+withdrawValue) {
      Toast.show({
        icon: 'loading',
        content: '提现提交中...',
        maskClickable: false
      })
      ApplyWithdraw({ money: withdrawValue })
        .then((res) => {
          if (res.code === 1) {
            getInfo()
            setWithdrawVisible(false)
            navigate('/result')
          } else {
            Toast.show({
              icon: 'fail',
              content: res.message,
              maskClickable: false
            })
          }
        })
        .catch((reason) => {
          Toast.show({
            icon: 'fail',
            content: reason.message || '服务器异常',
            maskClickable: false
          })
        })
        .finally(() => {})
    } else {
      Toast.show({
        content: '当前无可提金额'
      })
    }
  }

  const toCashWithdrawal = () => {
    console.log('user_info', userInfo)
    if (+userInfo?.is_idcard === 1) {
      console.log('签约状态：' + userInfo.bank_account + '刷脸状态' + userInfo?.is_fase_order)
      if (userInfo.bank_account.length > 0 && +userInfo?.is_fase_order === 1) {
        console.log('已签约')
        if (+userInfo?.is_pig_sign === 1) {
          // applyData()
          setStep(2)
        } else {
          console.log('未签约准备请求签约')
          getPigSignInfo()
        }
      } else {
        console.log('未签约')
        appSdk('jumpToRealBank', null, (result) => {
          console.log('成功回调，拿到的参数是', result)
          getInfo()
          const data = typeof result === 'string' ? JSON.parse(result) : result
          Toast.show({
            icon: data.status === 'success' ? 'success' : 'fail',
            content: data.status === 'success' ? '认证成功' : data?.message || '认证失败'
          })
        })
      }
    } else {
      // appSdk('jumpToRealName')
      setRealVisible(true)
    }
  }

  const turnMoneyFun = () => {
    if (+turnValue > 0) {
      if (+turnValue <= +userInfo.mibi) {
        ToTurnMoney({ mibi: turnValue })
          .then((res) => {
            console.log(res)
            getInfo()
            Toast.show({
              content: '请求成功',
              icon: 'success'
            })
          })
          .finally(() => setTurnVisible(false))
      } else {
        Toast.show({
          content: '余额不足'
        })
      }
    } else {
      Toast.show({
        content: '无效的金额'
      })
    }
  }

  // 计算可提现金额
  const countMoney = () => {
    const { service_fee, withdrawable_balance } = userInfo
    if (!Number(withdrawValue) || Number(withdrawable_balance) < 0) return '0.00'
    if (!Number(service_fee)) return withdrawValue || '0.00'
    return (withdrawValue - (service_fee / 100) * withdrawValue).toFixed(2)
    // return ((withdrawValue) * (1 - (service_fee / 100))).toFixed(2) || 0
  }

  return (
    <div className="mine_income">
      {/* other={
        <span onClick={() => navigate(`/record_list?type=${step === 1 ? 'income' : 'withdraw'}`)}>明细</span>
      } */}
      <NavBar title={step === 1 ? <NavTab navigate={navigate} /> : '收益提现'} />
      {step === 1 ? (
        <div>
          {/* <div className='mine_card income_detail'>
              <div className="content">
                <div className="wallet">{userInfo?.mibi || 0}</div>
                <p className='txt'>收到的{window.baseConfig.coin_name}值</p>
              </div>
            </div> */}
          {/* <div className='mine_card income_detail'>
              <div className="content">
                <div className="wallet">{userInfo?.withdrawable_balance || 0}</div>
                <p className='txt'>可提现金额</p>
              </div>
            </div> */}
          {/* <div className='mine_card income_detail'>
              <div className="content">
                <div className="wallet">{userInfo?.mibi || 0}</div>
                <p className='txt'>可转换的{window.baseConfig.coin_name}</p>
              </div>
              <div className="turn_btn" onClick={() => setTurnVisible(true)}>一键转换</div>
            </div> */}
          <div className="wallet_boxs">
            <div className="in-box yue">
              <div className="tit">
                <span className="t" onClick={() => navigate('/recharge_v2')}>
                  账户余额
                </span>
                <span className="tip" onClick={() => navigate(`/record_list?type=dou`)}>
                  余额明细
                </span>
              </div>
              <div className="data">
                <span className="z">{Math.trunc(userInfo?.mizuan || 0)}</span>
                <span className="dot">.{userInfo?.mizuan - userInfo?.mizuan}</span>
                <div className="icon"></div>
              </div>
            </div>
            <div className="in-box income">
              <div className="tit">
                <span className="t">账户收益</span>
                <span className="tip" onClick={() => navigate('/record_list?type=income')}>
                  收益明细
                </span>
              </div>
              <div className="data">
                <span className="z">{Math.trunc(userInfo?.mibi || 0)}</span>
                <span className="dot">.{userInfo?.mibi ? userInfo?.mibi.toString().split('.')[1] : 0}</span>
              </div>
            </div>
          </div>
          <div className="det_title">收益明细（一周）</div>
          <ExchangeLog proType="income" inPage />
        </div>
      ) : (
        <div>
          <div className="mine_card card">
            <div className="tit">{chooseMethod ? (chooseMethod?.type === 1 ? '到账银行卡' : '到账支付宝') : '选择提现方式'}</div>
            <div className="line"></div>
            <div className="content" onClick={onSelectBank}>
              <div className="card_info">{chooseMethod?.type === 1 ? chooseMethod?.bank_name : chooseMethod?.ali_account || ''}</div>
              <span className="tips">48小时之内到账</span>
            </div>
            <div className="arrow_icon"></div>
          </div>
          <div className="mine_card income">
            <div className="tit">提现金额</div>
            {/* <div className="line"></div> */}
            <div className="content">
              {/* <div className="wallet">{userInfo?.withdrawable_balance || 0}</div> */}
              <div className="wallet">
                <Input
                  type="number"
                  // value={withdrawValue}
                  onChange={setWithdrawValue}
                  onBlur={(e) => setWithdrawValue(Math.floor(+e.target.value))}
                  // onBlur={(v) => setWithdrawValue(Math.floor(v))}
                  min={1}
                  max={Math.floor(userInfo?.withdrawable_balance)}
                  value={withdrawValue}
                />
              </div>
            </div>
          </div>
          <div className="less_money">
            可提现金额：<span>{userInfo?.withdrawable_balance || 0}</span>
          </div>
        </div>
      )}
      <div className="fixed_content">
        {/* <div className='tips tips_txt'><p>{window.baseConfig.package_name}严禁未成年人进行充值，请阅读<a href='https://www.amengtec.com/protocol/dou_agreement' style={{ color: '#AFFBA1', textDecoration: 'none' }}>《{window.baseConfig.package_name}充值协议》</a></p></div> */}
        {step === 1 ? (
          <div className="btn small turn" onClick={() => setTurnVisible(true)}>
            收益转换
          </div>
        ) : null}
        {+userInfo?.is_union_member ? (
          <div
            className={step === 1 ? 'btn small withdraw' : 'btn'}
            onClick={
              step === 1
                ? toCashWithdrawal
                : () => {
                    if (+withdrawValue) {
                      setWithdrawVisible(true)
                    } else {
                      Toast.show({
                        content: '请输入提现金额'
                      })
                    }
                  }
            }
          >
            {step === 1 ? '收益提现' : '确定提现'}
          </div>
        ) : null}
      </div>

      <AmePopup visible={visible} AmePopupClose={setVisible}>
        <div className="bank_pop_content">
          <div className="bank_title">选择提现方式</div>
          <div className="banks">
            <div
              className="bank_item"
              onClick={() => {
                navigate('/person_list?type=2')
              }}
            >
              <div className="icon">
                <img src={aliImg} alt="" width={36} height={36} />
              </div>
              <div className="bank_info">
                <div className="bank_name">提现到支付宝账户</div>
                <span className="tips">48小时之内到账</span>
              </div>
            </div>
            <div
              className="bank_item"
              onClick={() => {
                navigate('/person_list?type=1&user_type=1')
              }}
            >
              <div className="icon">
                <img src={bankImg} alt="" width={36} height={36} />
              </div>
              <div className="bank_info">
                <div className="bank_name">提现到银行卡</div>
                <span className="tips">48小时之内到账</span>
              </div>
            </div>
          </div>
        </div>
      </AmePopup>

      <AmeModal
        visible={realVisible}
        title="请先完善实名认证信息"
        confirmText="认证"
        onCancel={() => setRealVisible(false)}
        onConfirm={() => {
          appSdk('jumpToRealName', null, (result) => {
            console.log('成功回调，拿到的参数是', result)
            getInfo()
            setRealVisible(false)
            if (typeof result === 'string') {
              const data = JSON.parse(result)
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败'
              })
            }
            if (typeof result === 'object') {
              const data = result
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败'
              })
            }
          })
        }}
      >
        <div>认证后方可进行提现操作</div>
      </AmeModal>
      <AmeModal
        visible={turnVisible}
        className="modal2 turn_modal"
        title="确定转换信息"
        confirmText="确认"
        onCancel={() => setTurnVisible(false)}
        onConfirm={turnMoneyFun}
      >
        <div className="sub_tit">点击输入转换金额</div>
        <div className="turn_input">
          <Input
            // type="number" // 正则 不能加number
            onChange={(e) => {
              setTurnValue(e.replace(/[^\d]/g, ''))
              // if (e.includes('.'))  {
              //   setTurnValue((e).replace(".", ''))
              // } else {
              //   setTurnValue((e).replace(/^0+/, ''))
              // }
            }}
            // onBlur={(e) => setTurnValue(Math.floor(+e.target.value) * 1)}
            min={1}
            // pattern='[0-9]*'
            // max={Math.floor(+userInfo?.mibi)}
            value={turnValue ? turnValue : ''}
          />
          <div className="icon"></div>
        </div>
      </AmeModal>

      <AmeModal
        visible={withdrawVisible}
        className="modal2"
        title={<div>确定提现信息</div>}
        confirmText="确认"
        onCancel={() => setWithdrawVisible(false)}
        onConfirm={applyData}
      >
        {/* <div className='sub_tit'>点击输入提现金额</div> */}
        <div className="money" style={{ marginTop: 10 }}>
          <span>￥</span>
          {countMoney()}
        </div>
        <div className="fee_tips">
          <p>
            <span>服务费</span>
            <span>{(+withdrawValue * (userInfo?.service_fee / 100)).toFixed(2)}</span>
          </p>
          <p>
            <span>服务及个人税费</span>
            <span>{+userInfo?.service_fee || 0}%</span>
          </p>
        </div>
      </AmeModal>
    </div>
  )
}

export default Income
